#CrowTaobaoPrice.py
import requests
import re

# 提交商品搜索请求，循环获取页面
def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        # print(r.status_code)
        r.raise_for_status()
        # print(r.encoding)
        r.encoding = r.apparent_encoding
        # print(r.encoding)
        return r.text
    except:
        print("爬取失敗")
        return ""

# 对于每个页面，提取商品名称和价格信息
def parsePage(ilt, html):
    try:
        # 双引号要反斜杠
        # 获取键值对 "view_price":"33.90"
        # \d 数字 等价于[0‐9]
        # "view_price":"[\d\.]*"
        # *  前一个字符0次或无限次扩展
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
        # 获取键值对 "raw_title":"金士顿U盘 32gu盘 USB3.0 移动U盘 32g高速正品优盘 学生正版∪盘"
        # *? 前一个字符0次或无限次扩展，最小匹配
        # \".*?\" 两个引号之间有任何单个字符
        # "raw_title":".*?"
        tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)
        # 啥也没有？？？
        print(plt)
        for i in range(len(plt)):
            # split(':')[1] 获得 键值对后半部分
            # eval 去掉双引号
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([price, title])
    except:
        print("提取价格名称失败")

# 将信息输出到屏幕上
def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}"
    print(tplt.format("序号", "价格", "商品名称"))
    # 序号
    count = 0
    for g in ilt:
        count = count + 1
        print(tplt.format(count, g[0], g[1]))
        
def main():
    goods = '书包'
    depth = 3
    start_url = 'https://s.taobao.com/search?q=' + goods
    infoList = []
    for i in range(depth):
        try:
            # 每页44个商品
            url = start_url + '&s=' + str(44*i)
            print(url)
            html = getHTMLText(url)
            parsePage(infoList, html)
        except:
            continue
    printGoodsList(infoList)
    
main()
